package cc.rengu.igas.channel.cups.common.util;

import cc.rengu.igas.channel.cups.common.constant.CupsParamConstant;
import cc.rengu.jradp.exception.SystemException;

import java.io.UnsupportedEncodingException;

/**
 * @author lizhangtao
 * @date 2020/12/05
 * <p>
 * mod by lizhangtao 2020/12/05
 */
public class MacFieldProcUtil {

    static public byte[] macProc(byte[] in) {
        if (in == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < in.length; i++) {
            //将小写字母转换为大写字母
            if (in[i] > 96 && in[i] < 123) {
                in[i] = (byte) (in[i] - 32);
            }
            //除了字母(A-Z),数字(0-9),空格,逗号(,),点号(.)以外的字符都删去
            if (in[i] > 64 && in[i] < 91) {
                stringBuilder.append((char) in[i]);
            } else if (in[i] > 47 && in[i] < 58) {
                stringBuilder.append((char) in[i]);
            } else if (in[i] == 32) {
                stringBuilder.append((char) in[i]);
            } else if (in[i] == 44) {
                stringBuilder.append((char) in[i]);
            } else if (in[i] == 46) {
                stringBuilder.append((char) in[i]);
            }
        }
        //删去起始空格和结尾空格
        String tmp = stringBuilder.toString().trim();

        //多余一个的连续空格，由一个空格代替
        byte[] b;
        try {
            b = tmp.getBytes(CupsParamConstant.GB18030);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new SystemException("不支持的编码格式" + CupsParamConstant.GB18030);
        }
        byte[] o = new byte[b.length];
        int j = 0;
        boolean flag = false;
        for (byte value : b) {
            if (value != 32) {
                o[j] = value;
                j++;
                flag = false;
            } else if (!flag) {
                //该段第一次遇到空格
                o[j] = value;
                j++;
                flag = true;
            }  //该段第N次遇到空格
            //不赋值

        }

        //做完以上步骤添加一个空格
        byte[] out = new byte[j + 1];
        System.arraycopy(o, 0, out, 0, j);
        out[j] = 32;
        return out;
    }
}
